import { Component, OnInit, OnDestroy, ViewChild, ElementRef, SimpleChange, ViewChildren } from '@angular/core';
import { List } from 'linqts';
import { DatePipe } from '@angular/common';
import { Farm } from '../../../entity/farm.model';
import { TurbStatus } from '../../../entity/turbstatus.model';
import { LimitedFarm } from '../main/limited-farm';
import { RealtimePowerPanelComponent } from '../main/realtime-power-panel/realtime-power-panel.component';
import { TurbstatusData, TurbstatusRow, TurbstatusColumn, TurbstatusTable } from '../main/turbstatus-panel/turbstatus-panel.component';
import { FarmService } from '../../../service/farm.service';
import { TurbStatusService } from '../../../service/turbstatus.service';
import { FarmPlantPowerService } from '../../../service/farm-plant-power.service';
import { DeviceService } from '../../../service/device.service';
import { CircuitService } from '../../../service/circuit.service';
import { PhaseService } from '../../../service/phase.service';
import { Setofvalue } from '../../../entity/setofvalue.model';
import { Device } from '../../../entity/device.model';
import { LimitedTurbine, SubStateVOList } from './limited-turbine';
import { TagData } from '../../../entity/tag-data.model';
import { Circuit } from '../../../entity/circuit.model';
import { Phase } from '../../../entity/phase.model';
import { LimitedPhases } from '../turbine-list/limited-phases';
import { LimitedCircuit } from '../turbine-list/limited-circuit';
import { LimitedTurbStatus } from '../turbine-list/limited-turbStatus';
import { Router, ActivatedRoute } from '@angular/router';
import { DataSourceService } from '../../../service/data-source/data-source.service';
import { Http } from '@angular/http';
import { TurbineComponent } from './turbine/turbine.component';
import { ApplicationService } from '../../../service/application.service';
import { TurboperCategory } from '../../../entity/turboper-category.model';
import { TurboperCurrent } from '../../../entity/turboper-current.model';
import { TurboperCategoryService } from '../../../service/turboper-category.service';
import { TurboperHistory } from '.././../../entity/turboper-history.model'
import { TurboperHistoryService } from '../../../service/turboper-history.service';
import { InterceptorService } from '../../../service/interceptor/interceptor-service';

@Component({
  selector: 'app-turbine-list',
  templateUrl: './turbine-list.component.html',
  styleUrls: ['./turbine-list.component.css'],
})
export class TurbineListComponent implements OnInit {
  @ViewChild('content')
  main: ElementRef;
  @ViewChildren(TurbineComponent)
  TurbineComp: TurbineComponent[];
  private fomat: string = 'yyyy-MM-dd HH:mm:ss';
  colorString: string = '#a6a3a3';

  substateActive: number = 0;
  private operCategorys: TurboperCategory[];//所有的子状态
  operCategoryEnable: TurboperCategory[];//所有启用的子状态
  /**
   * 所有选中项对应的风机列表
   * 
   * @type {LimitedTurbine[]}
   * @memberof TurbineListComponent
   */
  public allCheckTurbineList: LimitedTurbine[] = [];

  /**
   * 风机数据模型
   * 
   * @type {LimitedTurbine[]}
   * @memberof TurbineListComponent
   */
  public limitedTurbinies: LimitedTurbine[] = [];
  // public turbinies:Turbine[] = [];
  /**
   * 当前风场 
   * 
   * @type {LimitedFarm}
   * @memberof TurbineListComponent
   */
  public currentFarm: LimitedFarm;


  farm: Farm;
  farmId: number = 0;
  active: number = null;
  /**
   * 线路数据
   * 
   * @type {LimitedCircuit[]}
   * @memberof TurbineListComponent
   */
  public limitedCircuits: LimitedCircuit[] = [];
  public tempLimitedCircuits: LimitedCircuit[] = [];
  // public circuits:Circuit[] = [];
  public result: LimitedCircuit[] = [];
  /**
   * 分期数据
   * 
   * @type {LimitedCircuit[]}
   * @memberof TurbineListComponent
   */
  public limitedPhases: LimitedPhases[] = [];
  public tempLimitedPhases: LimitedPhases[] = [];
  /**
   * 风机状态数据
   * 
   * @type {LimitedTurbStatus[]}
   * @memberof TurbineListComponent
   */
  public limitedTurbstatus: LimitedTurbStatus[] = [];


  /**
   * 倍率
   * 
   * @public
   * @type {number}@memberof MainComponent
   */
  public ratio: number = 1;

  /**
   * 数据源服务
   * 
   * @private
   * @type {DataSourceService}
   * @memberof TurbineListComponent
   */
  private dataSource: DataSourceService;
  // triangleBottom: boolean = false;
  // triangleRight: boolean = false;

  /**
   * 风机列表
   * 
   * @type {Turbine[]}
   * @memberof TurbineListComponent
   */
  turbines: Device[] = [];

  /**
   * 是否显示风机状态详情
   * 
   * @type {boolean}
   * @memberof TurbineListComponent
   */
  showDetail: boolean = false;

  /**
   * 
   * 
   * @type {TurbineData}
   * @memberof TurbineListComponent
   */
  turbineDetailConf: TurbineData;

  /**
   * 当前选中的风机
   * 
   * @type {LimitedTurbine}
   * @memberof TurbineListComponent
   */
  currentTurbine: LimitedTurbine;

  /**
   * 当前时间
   * 
   * @type {Date}
   * @memberof TurbineListComponent
   */
  date: Date;

  /**
   * 
   * 
   * @type {number}
   * @memberof TurbineListComponent
   */
  onActive: number = 0;

  /**
   * 是否显示弹出层
   * 
   * @type {boolean}
   * @memberof TurbineListComponent
   */
  displayDialog: boolean;

  /**
   * 选中子状态的下标
   * 
   * @type {number}
   * @memberof TurbineListComponent
   */
  turboperActive: number = null;
  /**
   * 是否显示子状态详细信息
   * 
   * @type {boolean}
   * @memberof TurbineListComponent
   */
  isShowCategory: boolean;
  /**
   * 风机缩放值最大1，最小0
   * 
   * @memberof TurbineListComponent
   */
  zoom = 1;
  showMainTurb = false;
  /* selectedTurbCompNew: any;
  selectedTurbComp: any;
  currentOperCurrents: TurboperCurrent[];
  OperCurrentsList: TurboperCurrent[];
  operDesc: string;
  selectTurbComp: number; */
  /* turboperHistoryList: TurboperHistory[] */
  constructor(
    private application: ApplicationService,
    private http: InterceptorService,
    private phaseService: PhaseService,
    private circuitService: CircuitService,
    private TurbStatusService: TurbStatusService,
    private datePipe: DatePipe,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private operCategorysService: TurboperCategoryService,
    private deviceService: DeviceService,
    private turbHistSer: TurboperHistoryService,
  ) {

  }

  ngOnInit(): void {
    if (this.application.appConfigData.appCompany) {
      const appCompany = this.application.appConfigData.appCompany;
      if (appCompany === 'jl') {
        this.showMainTurb = true;
      } else {
        this.showMainTurb = false;
      }
    }
    if (this.application.currentApplicationParams && this.application.currentApplicationParams['ratio']) {
      this.ratio = Number(this.application.currentApplicationParams['ratio'].paramValue);
    }
    //是否显示子状态
    if (this.application.currentMenuParams && this.application.currentMenuParams['isShowCategory']) {
      this.isShowCategory = this.application.currentMenuParams.isShowCategory.paramValue == '1' ? true : false;
    } else {
      this.isShowCategory = false;
    }
    /* this.turboperHistory.getOperHistorysList()
      .then(res => {
        this.turboperHistoryList = [...res];
      })
      .catch(err => {
        console.log(err)
      }) */
    let farms: Farm[] = this.application.currentUserFarms.filter(farm => farm.farmCategory === 'winfarm');
    //window.sessionStorage.setItem('currentUserProfile', JSON.stringify(currentUserProfile))

    this.activatedRoute.params.subscribe((params: { farmId: number }) => {

      if (Number(params.farmId)) {
        this.farmId = Number(params.farmId);
      } else {

        if (window.sessionStorage.getItem('turblist')) {
          this.farmId = Number(window.sessionStorage.getItem('turblist'));
        } else {
          this.farmId = farms[0].farmId;

        }
      };
      window.sessionStorage.setItem('turblist', this.farmId.toString());
    });

    this.operCategorysService.getTurboperCategorys()
      .then(res => {

        if (!res) { return false; };
        this.operCategorys = [...res];
        this.operCategoryEnable = this.operCategorys.filter(operCategory => operCategory.enabled === true).sort((a, b) => a.operCategorySeq - b.operCategorySeq);

      })
      .catch(err => {
        console.log(err);
      });


  }

  ngOnDestroy(): void {
    if (this.dataSource != null) {
      this.dataSource.dispose();
    };
  }
  /**
   * 加载数据
   * 
   * 
   * @private
   * 
   * @memberof TurbineListComponent
   */
  private loadData(farm: Farm) {
    this.farm = farm;
    if (this.dataSource != null) {
      this.dataSource.dispose();
    }
    this.dataSource = new DataSourceService(this.http, this.datePipe);

    this.createLimitedFarm(farm);

    const turbstatusGet: Promise<TurbStatus[]> = this.TurbStatusService.getTurbStatus(), /* 风机状态列表 */
      phaseGet: Promise<Phase[]> = this.phaseService.getPhasesByfarmId(farm.farmId), /* 通过farmId获取的分期 */
      //turbineGet: Promise<Turbine[]> = this.turbineService.getTurbinesByFarmSubstate(farm.farmId), /* 通过farmId获取的风机 */
      circuitGet: Promise<Circuit[]> = this.circuitService.getCircuitByFarmId(farm.farmId); /* 通过farmId获取的线路 */
    const devices = this.deviceService.getDevicesByFarmId(farm.farmId)
    Promise.all([turbstatusGet, phaseGet, devices, circuitGet])
      .then(res => {
        if (res[2]) {
          this.turbines = [...res[2]];
          this.createLimitedTurbStatus(res[0]);
          this.createLimitedPhases(res[1], res[2]);
          this.createLimitedCircuit(res[2], res[3]);
          this.createLimitedTurbine(res[2]);
          this.getTurbinesList();
        }


        //开始推数据
        this.dataSource
          .begin()
          .subscribe(
            next => {
              this.countTurbStatus();
              this.TurbineComp.forEach(val => {

                val.initData()
              })
            },
            error => {
              console.log('app-turbine-list', error);
            });


      })
      .catch(error => {
        console.log('app-turbine-list', error);
      });
  }


  /**
   * 创建风机状态数据
   * 
   * @private
   * @param {LimitedTurbStatus[]} limitedTurbstatus 风机状态数据
   * @param {TurbStatus[]} turbStatus 风机状态集合
   * @param {LimitedTurbine[]} limitedTurbinies 风机数据模型
   * @param {PushService} pushService 
   * @memberof TurbineListComponent
   */
  private createLimitedTurbStatus(turbStatus: TurbStatus[]) {
    if (!turbStatus) { return false; };
    this.limitedTurbstatus = [];
    turbStatus.forEach(turbStatu => {
      let limitedTurbstatu = {
        id: turbStatu.statusId,
        name: turbStatu.statusName,
        value: turbStatu.statusValue,
        color: turbStatu.statusColor,
        tole: 0,
        isChecked: false,
      }
      this.limitedTurbstatus.push(limitedTurbstatu)
    })

  }

  /**
   * 创建线路数据
   * 
   * @private
   * @param {Turbine[]} turbinies 风机集合
   * @param {Circuit[]} circuit 线路集合
   * @memberof TurbineListComponent
   */
  private createLimitedCircuit(turbinies: Device[], circuits: Circuit[]) {
    if (!circuits || !turbinies) return false;
    this.limitedCircuits = [];


    circuits.forEach(circuit => {
      var count = 0;
      turbinies.forEach(turbinie => {
        if (circuit.circuitId == turbinie.circuitId) {
          count++;
        }
      })
      let limitedCircuit = {
        id: circuit.circuitId,
        name: circuit.circuitName,
        value: count,
        phaseIds: circuit.phaseIds,
        isChecked: false
      }
      this.limitedCircuits.push(limitedCircuit)
    })
    this.result = [...this.limitedCircuits];
    this.tempLimitedCircuits = [...this.limitedCircuits];
  }

  /**
   * 创建分期数据
   * 
   * @private
   * @memberof TurbineListComponent
   */
  private createLimitedPhases(phases: Phase[], turbine: Device[]) {
    if (!phases || !turbine) return false;

    this.limitedPhases = [];
    let WindSpeed = this.application.tagDict['MeanWindSpeed'];
    let Power = this.application.tagDict['Power'];

    phases.forEach(phase => {
      let limitedPhase: LimitedPhases = {
        id: phase.phaseId,
        name: phase.phaseName,
        value: turbine.filter(o => o.phaseId == phase.phaseId).length,
        windSpeed: this.dataSource.binding([this.currentFarm.farmCode, phase.phaseCode], WindSpeed),
        powers: this.dataSource.binding([this.currentFarm.farmCode, phase.phaseCode], Power),
        isChecked: false
      };
      this.limitedPhases.push(limitedPhase)
    })



    this.tempLimitedPhases = [...this.limitedPhases];

  }

  /**
   * 创建风场模型
   * 
   * @private
   * @param {Farm} farm 
   * @param {PushService} push 
   * @memberof TurbineListComponent
   */
  private createLimitedFarm(farm: Farm) {
    if (farm != null) {
      let GriFPower = this.application.tagDict['GriFPower'];
      let PowerDay = this.application.tagDict['PowerDay'];
      let WindSpeed = this.application.tagDict['MeanWindSpeed'];
      let Power = this.application.tagDict['Power'];
      let Communication = this.application.tagDict['Communication'];
      //创建风场数据模型
      this.currentFarm = new LimitedFarm();
      this.currentFarm.farmId = farm.farmId;
      this.currentFarm.farmCode = farm.farmCode;
      this.currentFarm.farmName = farm.farmName;
      this.currentFarm.farmCategory = farm.farmCategory;
      this.currentFarm.posx = farm.posx;
      this.currentFarm.posy = farm.posy;
      this.currentFarm.simpleCode = farm.simpleCode;
      this.currentFarm.capacity = farm.capacity;
      this.currentFarm.productionDate = farm.productionDate;
      this.currentFarm.totalTurbine = farm.totalTurbine;

      //创建实时数据点
      this.currentFarm.powerDay = this.dataSource.binding([farm.farmCode], PowerDay);
      this.currentFarm.avgWindSpeed = this.dataSource.binding([farm.farmCode], WindSpeed);
      this.currentFarm.totalPower = this.dataSource.binding([farm.farmCode], Power);
      this.currentFarm.communication = this.dataSource.binding([farm.farmCode], Communication);
    }

  }

  /**
   * 创建一个风机模型
   * 
   * @private
   * @param {Turbine[]} turbinies 
   * @param {TagNode} farmNode 
   * @param {PushService} push 
   * @memberof TurbineListComponent
   */
  private createLimitedTurbine(turbinies: Device[]) {
    if (!turbinies) return false
    this.limitedTurbinies = [];
    if (this.currentFarm != null) {
      let ActivePower = this.application.tagDict['ActivePower'];//有功功率
      let WindSpeed = this.application.tagDict['WindSpeed'];//平均风速
      let TurbineStatus = this.application.tagDict['TurbineStatus'];//风机状态
      let subState = this.application.tagDict['GP'];//子状态
      turbinies.forEach(turbine => {
        turbine.farmName = this.farm.farmName;
        let limitedTurbine: LimitedTurbine = {
          name: turbine.deviceName.substr(1),
          weed: this.dataSource.binding([this.currentFarm.farmCode, turbine.deviceCode], WindSpeed),
          griPower: this.dataSource.binding([this.currentFarm.farmCode, turbine.deviceCode], ActivePower),
          turbineStatus: this.dataSource.binding([this.currentFarm.farmCode, turbine.deviceCode], TurbineStatus),
          turbStatusColor: '#23d678',
          phaseId: turbine.phaseId,
          circuitId: turbine.circuitId,
          device: turbine,
          //subStateVOList: turbine.subCurStateVOList,
          turbSubState: this.dataSource.binding([this.currentFarm.farmCode, turbine.deviceCode], subState)
        }
        this.limitedTurbinies.push(limitedTurbine);
      })
    }

    this.allCheckTurbineList = this.limitedTurbinies;

  }

  /**
   * 统计风机状态
   * 
   * @private
   * @memberof TurbineListComponent
   */
  private countTurbStatus() {
    this.limitedTurbinies.forEach(turbine => {
      let index = this.limitedTurbstatus.findIndex(o => o.value == turbine.turbineStatus.value);
      if (index >= 0) {
        turbine.turbStatusColor = this.limitedTurbstatus[index].color;
      }
      else {
        // 未知
        turbine.turbStatusColor = this.colorString;
      }

    });
    // 统计风机状态对应的风机数量
    this.limitedTurbstatus.forEach(turbstatus => {
      let list = new List(this.limitedTurbinies);
      turbstatus.tole = list.Count(o => o.turbineStatus.value == turbstatus.value)
    });
    // console.log(this.limitedTurbstatus)
    this.getTurbinesList();

  }

  /**
   * 风机状态点击事件
   * 
   * @param {*} e 
   * @param {LimitedTurbStatus} turbineStatu 
   * @memberof TurbineListComponent
   */
  public turbStatuClick(e: any, turbineStatu: LimitedTurbStatus) {
    turbineStatu.isChecked = turbineStatu.isChecked ? false : true;
    this.getTurbinesList()
  }

  /**
   * 分期列表点击事件
   * 
   * @param {*} e 
   * @param {LimitedPhases} phase 
   * @memberof TurbineListComponent
   */
  public phaseClick(e: any, phase: LimitedPhases) {
    phase.isChecked = phase.isChecked ? false : true;
    this.getTurbinesList();
    //----------------------
    // this.checkCircuits(phase)
  }
  /**
     * 集成电路点击事件
     * 
     * @param {*} e 
     * @param {LimitedCircuit} circuit 
     * @memberof TurbineListComponent
     */
  public circuitClick(e: any, circuit: LimitedCircuit) {
    circuit.isChecked = circuit.isChecked ? false : true;

    this.getTurbinesList()
  }

  /**
   * 获取对应的风机列表
   * 
   * @memberof TurbineListComponent
   */
  private getTurbinesList() {
    let checkTurbStatuList: LimitedTurbStatus[] = [];
    let checkTurPhaseList: LimitedPhases[] = [];
    let checkCircuitList: LimitedCircuit[] = [];

    checkTurbStatuList = this.limitedTurbstatus.filter(o => o.isChecked); //过滤选中的状态
    checkTurPhaseList = this.tempLimitedPhases.filter(o => o.isChecked);  //过滤选中的工期
    checkCircuitList = this.result.filter(o => o.isChecked);              //过滤选中的线路
    let limitedTurbinies: LimitedTurbine[] = [];
    let checked: boolean = false;
    this.operCategoryEnable.forEach(operCategory => {
      if (operCategory.isChecked) {
        checked = true;
        let limited: LimitedTurbine[] = this.limitedTurbinies.filter(limitedTurbinie => limitedTurbinie.turbSubState.value == parseInt(operCategory.operCategoryCode));
        limitedTurbinies.push(...limited);
      }
    });

    if (checkTurbStatuList.length > 0 || checkTurPhaseList.length > 0 || checkCircuitList.length > 0) {

      let listTemp: LimitedTurbine[];
      if (checked) {
        listTemp = limitedTurbinies;
      } else {
        listTemp = this.limitedTurbinies;
      }
      //将本地风机集合放入临时变量中

      if (checkTurbStatuList.length > 0) {

        let list = new List(checkTurbStatuList).Select(o => o.value).ToList();

        listTemp = listTemp.filter(o => list.Contains(o.turbineStatus.value));
        this.tempLimitedPhases.forEach(v => {
          v.value = 0;
        })
        this.tempLimitedCircuits.forEach(v => {
          v.value = 0;
        });
        listTemp.forEach(v => {
          let i = this.limitedPhases.findIndex(o => o.id == v.phaseId);
          if (i > -1) {
            this.tempLimitedPhases[i].value += 1;
          };
          i = this.limitedCircuits.findIndex(o => o.id == v.circuitId);
          if (i > -1) {
            this.tempLimitedCircuits[i].value += 1;
          };

        });


      } else {
        this.tempLimitedCircuits.forEach(v => {
          v.value = this.turbines.filter(o => o.circuitId == v.id).length;
        })
        this.tempLimitedPhases.forEach(v => {
          v.value = this.turbines.filter(o => o.phaseId == v.id).length;
        })

      }
      this.result = [...this.tempLimitedCircuits]
      if (checkTurPhaseList.length > 0) {
        let list = new List(checkTurPhaseList).Select(o => o.id).ToList();
        listTemp = listTemp.filter(o => list.Contains(o.phaseId));
        this.tempLimitedCircuits.forEach(v => {
          v.value = 0;
        });
        listTemp.forEach(v => {

          let i = this.limitedCircuits.findIndex(o => o.id == v.circuitId);
          if (i > -1) {
            this.tempLimitedCircuits[i].value += 1;
          };

        });
        this.result = this.tempLimitedCircuits.filter(o => o.value != 0);
      }
      if (checkCircuitList.length > 0) {
        let list = new List(checkCircuitList).Select(o => o.id).ToList();
        listTemp = listTemp.filter(o => list.Contains(o.circuitId));
      }

      this.allCheckTurbineList = listTemp;
    }
    else {
      if (checked) {
        this.allCheckTurbineList = limitedTurbinies;
      } else {
        this.allCheckTurbineList = this.limitedTurbinies;
      }
      if (this.allCheckTurbineList.length != limitedTurbinies.length) {



        this.result = [...this.limitedCircuits];             //页面绑定线路

        // this.tempLimitedPhases = [...this.limitedCircuits];  
        this.tempLimitedPhases = [...this.limitedPhases];//页面绑定工期

        this.limitedCircuits = [...this.limitedCircuits];

        this.tempLimitedCircuits.forEach(v => {
          v.value = this.turbines.filter(o => o.circuitId == v.id).length;
        });
        this.tempLimitedPhases.forEach(v => {
          v.value = this.turbines.filter(o => o.phaseId == v.id).length;
        });
      }
    }
    this.onResize();
  }

  /**
   * 风场选中项变化
   * 
   * @param {LimitedFarm} data 
   * 
   * @memberof TurbineListComponent
   */
  public onChangeFarm(farm: Farm) {
    if (farm != null) {
      window.sessionStorage.setItem('turblist', farm.farmId.toString());

      this.active = null;

      this.loadData(farm);
    }
  }
  /**
   * 点击子状态
   * 
   * @memberof TurbineListComponent
   */
  onCategory(turboperCategory: TurboperCategory) {
    turboperCategory.isChecked = !turboperCategory.isChecked;
    this.getTurbinesList();
  }
  /**
   * 风机双击事件
   */
  public ondblclick(item: Device) {
    this.router.navigate(['/monitor/turbdetail', item.farmId, item.deviceId]);
  }
  /**
   *浏览器窗口大小变化事件
   * 
   * @memberof TurbineListComponent
   */
  onResize() {

    const clientHeight = this.main.nativeElement.clientHeight - 55,
      clientWidth = this.main.nativeElement.clientWidth - 20,
      turbConunt = this.allCheckTurbineList.length;
    let count = Math.floor(clientWidth / 105) * Math.floor(clientHeight / 125);
    if (count < turbConunt) {
      count = Math.floor(clientWidth / (105 * 0.9)) * Math.floor(clientHeight / (125 * 0.9));
      if (count < turbConunt) {
        this.zoom = 0.8;
      } else {
        this.zoom = 0.9;
      }
    } else {
      this.zoom = 1;
    }
  }
  /*  private rightClick(ev: any, item: LimitedTurbine, i: number) {
    this.active = i;
    let l = ev.clientX - ev.offsetX;
    let t = ev.clientY - ev.offsetY;
    let clientWidth = document.body.clientWidth;
    let clientHeight = document.body.clientHeight;
    if ((l + 350 + 95) > clientWidth) {
      this.triangleRight = true;
    } else {
      this.triangleRight = false;
    }
    if ((t + 200) > clientHeight) {
      this.triangleBottom = true;
    } else {
      this.triangleBottom = false;
    }
    ev.returnValue = false;
    return false;

   } */
  /* private tabIsShow(ev: any) {
    this.active = null;
  } */
  /* childSaveChange() {
    this.active = null;
    this.loadData(this.farm)
  } */
  /* newDataSave($event) {
    ///this.loadData(this.farm)
    //this.getCurrent()
  } */
  /* getCurrent() {

    this.turbineService.getFarmSubstateByTurbineId(this.turbineDetailConf.turbine.turbineId)
      .then(res => {
        console.log(res);
        if (res) {
          let date = new Date()
        }
      })
  } */
  /* onInDetail(ev: TurbineData) {

    this.date = new Date();
    this.turbineDetailConf = ev;
    this.showDetail = true;
    this.active = null;
    
  } */
  /*  getHistory() {
     this.turboperHistory.getOperHistorysList()
       .then(res => {
         this.turboperHistoryList = [...res];
       })
       .catch(err => {
         console.log(err)
       })
   }
   getCurrent() {
     this.turbineService.getFarmSubstateByTurbineId(this.turbineDetailConf.turbine.turbineId)
       .then(res => {
         if (res) {
           let date = new Date()
           this.OperCurrentsList = [];
           res.forEach(o => {
 
             let oper: TurboperCurrent = {
               operCurrentId: 0,
               operGuid: '',
               turbineId: 0,
               operCategoryId: 0,
               userId: 0,
               operClinet: '',
               operIp: '',
               operStartTime: null,
               failureCategoryId: null,
               operEndTime: null,
               operPlanendTime: null,
               operAnalysis: null,
               operProcess: null,
               operDesc: null,
               eTime: null,
             }
             for (let prop in o) {
               if (prop == 'operEndTime') {
                 if(o[prop]){
                   oper.eTime = new Date(o[prop]);
                   oper[prop] = o[prop];
                 }else{
                   let date=new Date();
                   oper.eTime=date;
                   oper[prop] = this.datePipe.transform(new Date(date), this.fomat)
                 }
                 
               } else{
                 oper[prop] = o[prop];
               }
                 
 
               
             }
             this.OperCurrentsList.push(oper)
           })
           this.currentOperCurrents = [...res];
           this.isDefault()
         }
       })
   } */
  /* onColse(ev) {
    this.showDetail = false;
    this.loadData(this.farm);
    this.getCurrent()
  }
  onTabChange(i) {
    this.substateActive = i;
  } */
  /* currentSubStateVOList: SubStateVOList;
  historyStartTime: Date;
  historyEndTime: Date;
  onClickHeader(n: number) {
    this.onActive = n;
  } */
  /* save() {
    this.subState.operStartTime = this.datePipe.transform(new Date(this.historyStartTime), this.fomat);
    this.subState.operendTime = this.datePipe.transform(new Date(this.historyEndTime), this.fomat);
    this.turboperHistory.update(this.subState)
      .then(res => {
        console.log(res);
        this.getHistory();
        this.displayDialog = false;
      })
      .catch(err => {
        console.log(err)
      })
  } */

  /*   delete(item: TurboperHistory) {
      if (confirm('是否删除')) {
        this.turboperHistory.delete(item.operHistoryId)
          .then(res => {
            this.getHistory();
            this.displayDialog = false;
          })
          .then(err => {
            console.log(err)
          })
      }
    } */
  /*  subState: TurboperHistory;
   subStateHistory: TurboperHistory;
   onEdit(item: TurboperHistory) {
     this.subStateHistory = item;
     this.historyStartTime = new Date(item.operStartTime);
     this.historyEndTime = new Date(item.operendTime);
     this.subState = this.cloneCar(item);
     this.displayDialog = true;
   }
   cloneCar(c: TurboperHistory): TurboperHistory {
     let car: TurboperHistory = {
       userId: 0,
       failureCategoryId: 0,
       lossPower: null,
       operCategoryId: null,
       operDesc: null,
       operClinet: '',
       operIp: '',
       operHistoryId: null,
       operPlanEndTime: null,
       operStartTime: null,
       operendTime: null,
       operguId: '',
       stopTime: 0,
       turbineId: 0,
       operAnalysis: null,
       operProcess: null,
     };
     for (let prop in c) {
       car[prop] = c[prop];
     }
     return car;
   }
   onEditColse() {
     this.displayDialog = false;
   }
   onCogState(item: TurboperCategory, index: number) {
     if (item.isDefault) return false;
     this.turboperActive = index;
   }
   onSave() {
     this.OperCurrentsList.forEach((value, index) => {
       let isChange: boolean = false;
       let names: string[] = Object.getOwnPropertyNames(value);
       
       for (let i: number = 0; i < names.length; i++) {
         let name = names[i];
         
         if (this.currentOperCurrents[index].hasOwnProperty(name)&&name!='operEndTime') {
           let v = Object.getOwnPropertyDescriptor(this.currentOperCurrents[index], name).value;
           
           if (v != value[name]) {
             isChange = true;
           }
         }
         if(value.eTime.getTime()!=new Date(value.operEndTime).getTime()){
           isChange=true;
         }
       }
       
       if (isChange) {
         value.operEndTime = this.datePipe.transform(value.eTime, this.fomat);
         this.turboperCurrent.update(value)
           .then(res => {
             if (res) {
               this.getCurrent()
             }
           })
           .catch(err => {
             console.log(err)
           })
       }
     })
     if (this.turboperActive != null) {
       let subState = this.turbineDetailConf.turboperCategorys[this.turboperActive];
       let userInfo: User = this.application.currentUser;
       let turboperCurrent: TurboperCurrent = new TurboperCurrent(0, '', this.turbineDetailConf.turbine.turbineId, subState.operCategoryId, userInfo.userId, '', '', '')
       turboperCurrent.operDesc = this.operDesc;
       turboperCurrent.operStartTime = this.datePipe.transform(new Date(this.date), this.fomat);
       turboperCurrent.failureCategoryId = this.selectTurbComp;
       this.turboperCurrent.create(turboperCurrent)
         .then(res => {
           if (res) {
             this.turboperActive = null;
             this.operDesc = null;
             this.selectTurbComp = 0;
             this.loadData(this.farm)
             this.getCurrent()
           }
         })
     }
   }
   onMove(item: TurboperCurrent) {
     this.turboperCurrent.delete(item.operCurrentId)
       .then(res => {
         this.substateActive = 0;
         this.loadData(this.farm)
         this.getCurrent()
       })
   }
   isDefault() {
     this.turbineDetailConf.turboperCategorys.forEach(turboperCategory => {
       let index = this.currentOperCurrents.findIndex(o => o.operCategoryId == turboperCategory.operCategoryId);
       if (index > -1) {
         turboperCategory.isDefault = true;
       } else {
         turboperCategory.isDefault = false;
       }
     })
   }
   onChange() {
 
     if (this.subStateHistory) {
       for (let o in this.subStateHistory) {
         if (this.subStateHistory[o] != this.subState[o]) {
           return false;
         }
       }
       if (this.historyStartTime.getTime() != new Date(this.subStateHistory.operStartTime).getTime() || this.historyEndTime.getTime() != new Date(this.subStateHistory.operendTime).getTime()) {
         return false;
       }
     }
     return true;
   }*/
}
export interface TurbineData {
  subStateVOList: SubStateVOList[],
  turbine: Device,
  turbineStatus: TagData,
  turboperCategorys: TurboperCategory[]
}





// WEBPACK FOOTER //
// ./src/app/module/monitor/turbine-list/turbine-list.component.ts